<template>
  <section class="todoapp">
    <hm-header @add-event="handleAdd"></hm-header>
    <hm-main
      :list="showList"
      @delete-event="handleDelete"
      @change-status-event="changeStatus"
      @change-all-event="handleAll"
    ></hm-main>
    <hm-footer
      :list="list"
      @clearall-event="clearAll"
      :status="status"
      @status-event="status = $event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
   components: {
        HmHeader,
        HmMain,
        HmFooter,
  },
  data() {
    return {
      list: JSON.parse(window.localStorage.getItem("list")) || [],
      //约定 all 代表的是全部 done 代表的显示已完成 undone 未完成
      status: obj[location.hash] || "all",
    };
  },

  methods: {
    handleDel(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeStatus(id) {
      let obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
  },
  handleAdd(name) {
    const id = this.list.length === 0 ? 1 : this.list.slice(-1)[0].id + 1;
    const obj = {
      id,
      name,
      done: false,
    };
    this.list.unshift(obj);
  },
  handleAll(value) {
    this.list = this.list.map((item) => {
      item.done = value;
      return item;
    });
  },
  clearAll() {
    this.list = this.list.filter((item) => item.done === false);
  },
  computed: {
    showDown() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "done") {
        return this.list.filter((item) => item.done === true);
      } else {
        return this.list.filter((item) => item.done === false);
      }
    },
  },
  watch: {
    list: {
      hander(newValue) {
        window.localStorage.setItem("list", JSON.stringify(newValue));
      },
      //开启深度监听
      deep: true,
    },
  },
};
</script>

<style></style>
